表单令牌
验证规则支持对表单的令牌验证,首先需要在你的表单里面增加下面隐藏域:
type="hidden" name="__token__" value="{$Request.token}" />
或者
{:token()}
然后在你的验证规则中,添加token验证规则即可,例如,如果使用的是验证器的话,可以改为:
protected $rule = ['name' => 'require|max:25|token','email' => 'email',];
如果你的令牌名称不是__token__,则表单需要改为:
type="hidden" name="__hash__" value="{$Request.token.__hash__}" />
或者:
{:token('__hash__')}
验证器中需要改为:
protected $rule = ['name' => 'require|max:25|token:__hash__','email' => 'email',];
如果需要自定义令牌生成规则,可以调用Request类的token方法,例如:
namespace app\index\controller;use think\Controller;class Index extends Controller{public function index(){$token = $this->request->token('__token__', 'sha1');$this->assign('token', $token);return $this->fetch();}}
然后在模板表单中使用:
type="hidden" name="__token__" value="{$token}" />
或者不需要在控制器写任何代码,直接在模板中使用:
{:token('__token__', 'sha1')}